<?php

namespace App\Services;

use App\Common\CommonConst;
use App\Exceptions\BusinessException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Collection;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Arr;

class BaseService
{
    public $page;

    public $perPage;

    public function __construct()
    {
    }

    /**
     * 转换列表数据中的creator、updator字段为人名
     *
     * @param  mixed $list
     * @param  array $fields
     * @return mixed
     *
     * @throws BusinessException
     * @throws BindingResolutionException
     */
    public function fillListUserName(mixed $list, array $fields = ['creator']): mixed
    {
        if (empty($fields)) {
            return $list;
        }

        $userIds = [];
        if ($list instanceof Collection) {
            foreach ($fields as $field) {
                $userIds = array_merge($userIds, $list->pluck($field)->toArray());
            }
        } else {
            foreach ($fields as $field) {
                $userIds = array_merge($userIds, array_column($list, $field));
            }
        }
        $userIds = array_filter(array_unique($userIds));

        /** @var SysUserService $sysUserService */
        $sysUserService = app()->make(SysUserService::class);
        $sysUsers = $sysUserService->getById($userIds);

        $userIdMapping = [];
        foreach ($sysUsers as $sysUser) {
            $userIdMapping[$sysUser->id] = $sysUser->username;
        }

        foreach ($list as &$value) {
            foreach ($fields as $field) {
                $value[$field . '_text'] = $userIdMapping[$value[$field]] ?? '未知';
            }
        }

        return $list;
    }

    /**
     * 转换单条数据中的creator、updator字段为人名
     *
     * @param  mixed $record
     * @param  array $fields
     * @return mixed
     *
     * @throws BusinessException
     * @throws BindingResolutionException
     */
    public function fillRecordUserName(mixed $record, array $fields = ['creator']): mixed
    {
        if (empty($fields)) {
            return $record;
        }

        $userIds = [];
        foreach ($fields as $field) {
            $userIds[] = $record[$field];
        }
        $userIds = array_filter(array_unique($userIds));

        /** @var SysUserService $sysUserService */
        $sysUserService = app()->make(SysUserService::class);
        $sysUsers = $sysUserService->getById($userIds);

        $userIdMapping = [];
        foreach ($sysUsers as $sysUser) {
            $userIdMapping[$sysUser->id] = $sysUser->username;
        }

        foreach ($fields as $field) {
            $record[$field . '_text'] = $userIdMapping[$record[$field]] ?? '未知';
        }

        return $record;
    }

    public function preparePageParams(array $params)
    {
        $this->page = $params['page'] ?? 1;
        $this->perPage = $params['per_page'] ?? CommonConst::PAGE_SIZE;

        if ($this->perPage > 100) {
            $this->perPage = 100;
        }
    }

    public function uploadMiniAppPic ($file, $fileName)
    {
        $now = Carbon::now();
        $path = Arr::join([
            'gbd-coupon',
            'uploads',
            'pic',
            'activity',
            $now->year,
            $now->month,
            $now->day,
        ], '/');
        $filePath = $path . '/' . $fileName;
        $resFileName = Storage::disk('tos_public')->put($filePath, $file);
        if(!$resFileName) {
            return false;
        }
        return 'https://outsource-public-read.tos-cn-beijing.volces.com/' .  $filePath;
    }

    /**
     * @desc Generate paginate meta info
     *
     * @param  Paginator $paginator
     * @return array
     */
    public function paginateMeta(Paginator $paginator): array
    {
        return [
            'current_page' => $paginator->currentPage(),
            'last_page' => $paginator->lastPage(),
            'per_page' => $paginator->perPage(),
            'total' => $paginator->total(),
        ];
    }
}
